﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Fashion.Common.Const;
using Fashion.Models;
using Fashion.Models.Interface;
using Fashion.Models.Model;

namespace Fashion.Controllers
{
    [Authorize(Roles = "Admin")]
    public class SubCategoryController : Controller
    {
        private IProductCategoryRepository _repository;
        public SubCategoryController()
        {
            _repository = new ProductCategoryRepository();
        }

        public ActionResult Index(int parentId)
        {
            var category = _repository.GetCategoryById(parentId);
            ViewData[ViewDataName.ParentId] = parentId;
            ViewData[ViewDataName.Name] = category.Name;
            return View(category.ProductCategories);
        }

        public ActionResult Create(int parentId)
        {
            ProductSubCategoryModel model = new ProductSubCategoryModel();
            model.ParentId = parentId;
            return View(model);
        }

        [HttpPost]
        public ActionResult Create(ProductSubCategoryModel model)
        {
            if (!ModelState.IsValid)
                return View(model);
            ProductCategory category = new ProductCategory();
            category.ParentId = model.ParentId;
            category.Name = model.Name;
            category.OrderDisplay = model.OrderDisplay;
            _repository.AddNewCategory(category);
            return RedirectToAction("Index", new { parentId=model.ParentId});
        }

        public ActionResult Update(int id)
        {
            var category = _repository.GetCategoryById(id);
            var model = new ProductSubCategoryModel
                            {
                                Id =  category.Id,
                                ParentId = (int)category.ParentId,
                                Name = category.Name,
                                OrderDisplay = category.OrderDisplay,
                            };
            return View(model);
        }

        [HttpPost]
        public ActionResult Update(ProductSubCategoryModel model)
        {
            if (!ModelState.IsValid)
                return View(model);
            var category = _repository.GetCategoryById(model.Id);
            category.Name = model.Name;
            category.OrderDisplay = model.OrderDisplay;
            _repository.Update();
            return RedirectToAction("Index", new { parentId = model.ParentId });
        }

        public ActionResult Delete(int id, int parentId)
        {
            _repository.DeleteCategory(id);
            return RedirectToAction("Index", new { parentId = parentId });
        }
    }
}
